package com.example.api.controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.common.CommonResult;
import com.common.auth.MemoryAuthenRepository;
import com.common.auth.MyAuthenRepository;
import com.common.auth.MyAuthenticationInfo;
import com.common.mybatis.gen.model.SysFunc;
import com.common.mybatis.gen.model.SysRole;
import com.common.mybatis.gen.model.SysUser;
import com.example.api.service.CustomSysUserService;
import com.example.myutil.EncryptionMD5;
import com.example.myutil.MyUtil;

import io.swagger.annotations.Api;

@RequestMapping("/open/api")
@RestController
@Validated
@Api(description = "开放接口")
public class OpenApiController {

	@Autowired
	private CustomSysUserService customSysUserServiceImpl;
	
	private MyAuthenRepository authenRepository = MemoryAuthenRepository.getInstance();
	
	@Value("app.auth.tokenExpireTime:86400")
	private String tokenExpiredTimeLong;
	
	@GetMapping("/authen")
  public CommonResult userAuthen(String userName, String password) 
	{
		CommonResult result = new CommonResult();
		MyAuthenticationInfo info = new MyAuthenticationInfo();
		if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
			result.setSuccess(false);
			result.setMessage("用户名和密码不能为空");
			return result;
		}
		
		SysUser user = customSysUserServiceImpl.getUserByName(userName);
		if(user != null){
			String md5Pass = EncryptionMD5.getMD5(password, "SHA-256");
			if(user.getPassword().equals(md5Pass)) {
				info.setAuthenticated(true);
				info.setUserId(user.getUserId());
				Date now = new Date();
				info.setToken(UUID.randomUUID().toString());
				info.setTokenCreateTime(now);
				info.freshTokenExpireTime(MyUtil.toLongSafe(tokenExpiredTimeLong));

				List<SysRole> roles = customSysUserServiceImpl.getUserSysRoles(user.getUserId());
			  
				if(roles != null && roles.size() > 0) {
					info.setRoles(roles);
					List<SysFunc> funcs = customSysUserServiceImpl.getUserSysFuncs(user.getUserId());
					info.setFuncs(funcs);
				}
				
			  //将token写到redis
				info = authenRepository.saveAuthenInfo(info);
				result.setSuccess(info.getAuthenticated());
				result.setData(info);
				if(!info.getAuthenticated()) {
					result.setMessage("用户名或密码错误");
				}
			}
		}
    return result;
  }
	
	@GetMapping("/logout")
  public CommonResult logout(Integer userId, String token) 
	{
		CommonResult result = new CommonResult();
		if(userId == null || StringUtils.isBlank(token)) {
			result.setSuccess(false);
			result.setMessage("userId and token required");
			return result;
		}
		
		MyAuthenticationInfo authen = authenRepository.getAuthenByToken(token);
		if(authen == null) {
			result.setSuccess(false);
			result.setMessage("invalid token");
			return result;
		}
		
		if(!userId.equals(authen.getUserId())){
			result.setSuccess(false);
			result.setMessage("token not match userId");
			return result;
		}
		
		authenRepository.removeAuthenInfo(token);
		
    return result;
  }
}
